package org.flown.shop.controller;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.flown.shop.SessionAttribute;
import org.flown.shop.dto.GoodsDTO;
import org.flown.shop.entity.Goods;
import org.flown.shop.entity.Seller;
import org.flown.shop.service.GoodsService;
import org.flown.shop.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


@RequestMapping("/seller")
@Controller
public class GoodsSellerController
{
    @Autowired
    private GoodsService service_goods;
    @Autowired
    private StoreService service_store;


    @ResponseBody
    @PostMapping(value = "/shelvesGoods", params = {"storeID", "name", "price"})
    public String shelvesGoods(HttpSession session, @Valid Goods goods)
    {
        Seller seller = (Seller)session.getAttribute(SessionAttribute.SELLER.getName());
        if (seller == null)
            return "未登录";
        if (this.service_store.getStoreByID(goods.getStoreID()).getSellerID() != seller.getID())
            return "上架商品的店铺与登录卖家店铺对不上号";

        goods.setSellerID(seller.getID());
        if (this.service_goods.insertGoods(goods) == 0)
            return "上架失败";
        return "上架成功";
    }



    @ResponseBody
    @PostMapping(value = {"/unShelveGoodsByID", "/unShelveGoodsByID/{goods_id}"})
    public String unShelveGoodsByID(HttpSession session, @PathVariable @RequestParam("id") int goods_id)
    {
        Seller seller = (Seller)session.getAttribute(SessionAttribute.STORE.getName());
        if (seller == null)
            return "未登录";

        GoodsDTO goods_dto = this.service_goods.getGoodsDTOByID(goods_id);
        if (goods_dto.getSellerID() != seller.getId())
            return "该商品与该店铺无关";

        this.service_goods.deleteGoodsByID(goods_id);
        if (this.service_goods.deleteGoodsByID(goods_id) == 0)
            return "下架失败";
        return "下架成功";
    }
}
